<template>
  <el-dialog
    v-model="visible"
    :title="`数据预览 - ${table?.name || ''}`"
    width="80%"
    :before-close="handleClose">
    
    <div class="data-preview-dialog">
      <div v-if="table" class="preview-content">
        <!-- 表信息 -->
        <div class="table-info">
          <div class="info-cards">
            <div class="info-card">
              <div class="card-label">表名</div>
              <div class="card-value">{{ table.name }}</div>
            </div>
            <div class="info-card">
              <div class="card-label">行数</div>
              <div class="card-value">{{ tableData.length }}</div>
            </div>
            <div class="info-card">
              <div class="card-label">列数</div>
              <div class="card-value">{{ table.fields?.length || 0 }}</div>
            </div>
            <div class="info-card">
              <div class="card-label">数据源</div>
              <div class="card-value">{{ getDataSourceName() }}</div>
            </div>
          </div>
          
          <div v-if="table.description" class="table-description">
            <el-text type="info">{{ table.description }}</el-text>
          </div>
        </div>
        
        <!-- 工具栏 -->
        <div class="preview-toolbar">
          <div class="toolbar-left">
            <el-input
              v-model="searchText"
              placeholder="搜索数据..."
              style="width: 300px"
              clearable>
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            
            <el-select
              v-model="selectedColumns"
              multiple
              placeholder="选择显示列"
              style="width: 200px"
              collapse-tags
              collapse-tags-tooltip>
              <el-option
                v-for="field in table.fields"
                :key="field.id"
                :label="field.name"
                :value="field.id" />
            </el-select>
          </div>
          
          <div class="toolbar-right">
            <el-button @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
            <el-button @click="exportData">
              <el-icon><Download /></el-icon>
              导出
            </el-button>
          </div>
        </div>
        
        <!-- 数据表格 -->
        <div class="data-table">
          <el-table
            :data="filteredData"
            style="width: 100%"
            height="400"
            stripe
            border
            :loading="loading">
            
            <el-table-column
              v-for="field in visibleFields"
              :key="field.id"
              :prop="field.id"
              :label="field.name"
              :width="getColumnWidth(field)"
              show-overflow-tooltip>
              
              <template #header="{ column }">
                <div class="column-header">
                  <el-icon class="field-icon">
                    <component :is="getFieldIcon(field)" />
                  </el-icon>
                  <span>{{ field.name }}</span>
                  <el-tag :type="getFieldTypeColor(field)" size="small">
                    {{ field.dataType }}
                  </el-tag>
                </div>
              </template>
              
              <template #default="{ row }">
                <div class="cell-content">
                  <span v-if="field.dataType === 'currency'" class="currency-value">
                    ¥{{ formatCurrency(row[field.id]) }}
                  </span>
                  <span v-else-if="field.dataType === 'date'" class="date-value">
                    {{ formatDate(row[field.id]) }}
                  </span>
                  <span v-else-if="field.dataType === 'number'" class="number-value">
                    {{ formatNumber(row[field.id]) }}
                  </span>
                  <span v-else class="text-value">
                    {{ row[field.id] }}
                  </span>
                </div>
              </template>
            </el-table-column>
            
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
        </div>
        
        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="filteredData.length"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
        
        <!-- 字段统计信息 -->
        <div class="field-statistics">
          <el-tabs v-model="activeStatTab" type="border-card">
            <el-tab-pane label="字段统计" name="fields">
              <div class="stats-grid">
                <div
                  v-for="field in table.fields"
                  :key="field.id"
                  class="stat-card">
                  
                  <div class="stat-header">
                    <el-icon class="field-icon">
                      <component :is="getFieldIcon(field)" />
                    </el-icon>
                    <span class="field-name">{{ field.name }}</span>
                    <el-tag :type="getFieldTypeColor(field)" size="small">
                      {{ field.dataType }}
                    </el-tag>
                  </div>
                  
                  <div class="stat-content">
                    <div v-if="field.dataType === 'number' || field.dataType === 'currency'" class="number-stats">
                      <div class="stat-item">
                        <span class="stat-label">最小值:</span>
                        <span class="stat-value">{{ getFieldMin(field.id) }}</span>
                      </div>
                      <div class="stat-item">
                        <span class="stat-label">最大值:</span>
                        <span class="stat-value">{{ getFieldMax(field.id) }}</span>
                      </div>
                      <div class="stat-item">
                        <span class="stat-label">平均值:</span>
                        <span class="stat-value">{{ getFieldAvg(field.id) }}</span>
                      </div>
                      <div class="stat-item">
                        <span class="stat-label">总和:</span>
                        <span class="stat-value">{{ getFieldSum(field.id) }}</span>
                      </div>
                    </div>
                    
                    <div v-else class="text-stats">
                      <div class="stat-item">
                        <span class="stat-label">唯一值:</span>
                        <span class="stat-value">{{ getUniqueCount(field.id) }}</span>
                      </div>
                      <div class="stat-item">
                        <span class="stat-label">空值:</span>
                        <span class="stat-value">{{ getNullCount(field.id) }}</span>
                      </div>
                    </div>
                    
                    <div class="stat-item">
                      <span class="stat-label">非空值:</span>
                      <span class="stat-value">{{ getNonNullCount(field.id) }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="数据质量" name="quality">
              <div class="quality-report">
                <div class="quality-summary">
                  <div class="quality-item">
                    <div class="quality-label">数据完整性</div>
                    <div class="quality-value">
                      <el-progress :percentage="getDataCompleteness()" />
                    </div>
                  </div>
                  
                  <div class="quality-item">
                    <div class="quality-label">数据一致性</div>
                    <div class="quality-value">
                      <el-progress :percentage="getDataConsistency()" />
                    </div>
                  </div>
                </div>
                
                <div class="quality-details">
                  <h5>数据质量问题</h5>
                  <div v-if="qualityIssues.length === 0" class="no-issues">
                    <el-result icon="success" title="数据质量良好" sub-title="未发现数据质量问题" />
                  </div>
                  <div v-else class="issues-list">
                    <div
                      v-for="issue in qualityIssues"
                      :key="issue.id"
                      class="issue-item">
                      <el-alert
                        :title="issue.title"
                        :description="issue.description"
                        :type="issue.severity"
                        show-icon
                        :closable="false" />
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      
      <div v-else class="no-table">
        <el-empty description="未选择表" />
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useDataModelStore } from '../../stores/dataModelStore'
import { ElMessage } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Download,
  Document,
  Coin,
  Calendar,
  Key,
  Link
} from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  table: {
    type: Object,
    default: null
  }
})

const emit = defineEmits(['update:modelValue'])

// 数据模型store
const dataModelStore = useDataModelStore()

// 响应式数据
const visible = ref(false)
const loading = ref(false)
const searchText = ref('')
const selectedColumns = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const activeStatTab = ref('fields')
const tableData = ref([])
const qualityIssues = ref([])

// 计算属性
const visibleFields = computed(() => {
  if (!props.table?.fields) return []
  
  if (selectedColumns.value.length === 0) {
    return props.table.fields
  }
  
  return props.table.fields.filter(field => 
    selectedColumns.value.includes(field.id)
  )
})

const filteredData = computed(() => {
  if (!searchText.value) return tableData.value
  
  const searchLower = searchText.value.toLowerCase()
  return tableData.value.filter(row => {
    return Object.values(row).some(value => 
      String(value).toLowerCase().includes(searchLower)
    )
  })
})

// 监听器
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val && props.table) {
    loadTableData()
  }
})

watch(visible, (val) => {
  emit('update:modelValue', val)
})

watch(() => props.table, (table) => {
  if (table && visible.value) {
    loadTableData()
  }
})

// 方法
const loadTableData = async () => {
  if (!props.table) return
  
  loading.value = true
  try {
    // 从store获取表数据
    tableData.value = dataModelStore.getTableData(props.table.id)
    
    // 初始化选中的列
    if (selectedColumns.value.length === 0 && props.table.fields) {
      selectedColumns.value = props.table.fields.slice(0, 8).map(f => f.id)
    }
    
    // 分析数据质量
    analyzeDataQuality()
  } catch (error) {
    console.error('加载表数据失败:', error)
    ElMessage.error('加载表数据失败')
  } finally {
    loading.value = false
  }
}

const getDataSourceName = () => {
  // 查找表所属的数据源
  for (const dataSource of dataModelStore.dataSources) {
    if (dataSource.tables?.some(t => t.id === props.table?.id)) {
      return dataSource.name
    }
  }
  return '未知'
}

const getFieldIcon = (field) => {
  if (field.isPrimaryKey) return Key
  if (field.isForeignKey) return Link
  if (field.dataType === 'number' || field.dataType === 'currency') return Coin
  if (field.dataType === 'date') return Calendar
  return Document
}

const getFieldTypeColor = (field) => {
  const colors = {
    'text': 'info',
    'number': 'warning',
    'currency': 'success',
    'date': 'primary',
    'boolean': 'danger'
  }
  return colors[field.dataType] || 'info'
}

const getColumnWidth = (field) => {
  const widths = {
    'text': 150,
    'number': 120,
    'currency': 120,
    'date': 140,
    'boolean': 80
  }
  return widths[field.dataType] || 150
}

const formatCurrency = (value) => {
  if (value == null) return '-'
  return Number(value).toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

const formatDate = (value) => {
  if (!value) return '-'
  try {
    return new Date(value).toLocaleDateString('zh-CN')
  } catch {
    return value
  }
}

const formatNumber = (value) => {
  if (value == null) return '-'
  return Number(value).toLocaleString('zh-CN')
}

const getFieldMin = (fieldId) => {
  const values = tableData.value.map(row => Number(row[fieldId])).filter(v => !isNaN(v))
  return values.length > 0 ? Math.min(...values).toLocaleString('zh-CN') : '-'
}

const getFieldMax = (fieldId) => {
  const values = tableData.value.map(row => Number(row[fieldId])).filter(v => !isNaN(v))
  return values.length > 0 ? Math.max(...values).toLocaleString('zh-CN') : '-'
}

const getFieldAvg = (fieldId) => {
  const values = tableData.value.map(row => Number(row[fieldId])).filter(v => !isNaN(v))
  if (values.length === 0) return '-'
  const avg = values.reduce((sum, v) => sum + v, 0) / values.length
  return avg.toLocaleString('zh-CN', { maximumFractionDigits: 2 })
}

const getFieldSum = (fieldId) => {
  const values = tableData.value.map(row => Number(row[fieldId])).filter(v => !isNaN(v))
  const sum = values.reduce((sum, v) => sum + v, 0)
  return sum.toLocaleString('zh-CN')
}

const getUniqueCount = (fieldId) => {
  const values = tableData.value.map(row => row[fieldId]).filter(v => v != null)
  return new Set(values).size
}

const getNullCount = (fieldId) => {
  return tableData.value.filter(row => row[fieldId] == null).length
}

const getNonNullCount = (fieldId) => {
  return tableData.value.filter(row => row[fieldId] != null).length
}

const getDataCompleteness = () => {
  if (!props.table?.fields || tableData.value.length === 0) return 100
  
  const totalCells = props.table.fields.length * tableData.value.length
  const nullCells = props.table.fields.reduce((sum, field) => 
    sum + getNullCount(field.id), 0
  )
  
  return Math.round(((totalCells - nullCells) / totalCells) * 100)
}

const getDataConsistency = () => {
  // 简单的数据一致性检查
  return 95 // 示例值
}

const analyzeDataQuality = () => {
  qualityIssues.value = []
  
  if (!props.table?.fields || tableData.value.length === 0) return
  
  // 检查空值过多的字段
  props.table.fields.forEach(field => {
    const nullCount = getNullCount(field.id)
    const nullPercentage = (nullCount / tableData.value.length) * 100
    
    if (nullPercentage > 50) {
      qualityIssues.value.push({
        id: `null_${field.id}`,
        title: `字段 "${field.name}" 空值过多`,
        description: `该字段有 ${nullPercentage.toFixed(1)}% 的空值`,
        severity: 'warning'
      })
    }
  })
  
  // 检查重复数据
  const duplicateRows = findDuplicateRows()
  if (duplicateRows > 0) {
    qualityIssues.value.push({
      id: 'duplicate_rows',
      title: '发现重复数据',
      description: `共有 ${duplicateRows} 行重复数据`,
      severity: 'warning'
    })
  }
}

const findDuplicateRows = () => {
  const seen = new Set()
  let duplicates = 0
  
  tableData.value.forEach(row => {
    const rowString = JSON.stringify(row)
    if (seen.has(rowString)) {
      duplicates++
    } else {
      seen.add(rowString)
    }
  })
  
  return duplicates
}

const refreshData = () => {
  loadTableData()
}

const exportData = () => {
  // 导出数据功能
  ElMessage.info('导出功能开发中...')
}

const handleSizeChange = (size) => {
  pageSize.value = size
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

const handleClose = () => {
  visible.value = false
}

onMounted(() => {
  if (props.modelValue && props.table) {
    loadTableData()
  }
})
</script>

<style scoped>
.data-preview-dialog {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.table-info {
  margin-bottom: 20px;
}

.info-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 12px;
}

.info-card {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  text-align: center;
}

.card-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.card-value {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.table-description {
  padding: 8px 12px;
  background: #ecf5ff;
  border-radius: 4px;
  border-left: 3px solid #409EFF;
}

.preview-toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e4e7ed;
}

.toolbar-left {
  display: flex;
  gap: 12px;
  align-items: center;
}

.toolbar-right {
  display: flex;
  gap: 8px;
}

.data-table {
  margin: 16px 0;
}

.column-header {
  display: flex;
  align-items: center;
  gap: 6px;
}

.field-icon {
  color: #909399;
}

.cell-content {
  display: flex;
  align-items: center;
}

.currency-value {
  color: #67C23A;
  font-weight: 500;
}

.number-value {
  color: #E6A23C;
  font-weight: 500;
}

.date-value {
  color: #409EFF;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

.field-statistics {
  margin-top: 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
  padding: 16px;
}

.stat-card {
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  background: white;
}

.stat-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f0f0f0;
}

.field-name {
  flex: 1;
  font-weight: 600;
  color: #303133;
}

.stat-content {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
}

.stat-label {
  color: #606266;
}

.stat-value {
  color: #303133;
  font-weight: 500;
}

.quality-report {
  padding: 16px;
}

.quality-summary {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 24px;
}

.quality-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.quality-label {
  font-weight: 600;
  color: #303133;
}

.quality-details h5 {
  margin: 0 0 16px 0;
  color: #303133;
}

.no-issues {
  text-align: center;
  padding: 20px;
}

.issues-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.no-table {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}
</style>

